package com.zrq.secondkill.controller;

import com.zrq.secondkill.controller.viewobject.UserVO;
import com.zrq.secondkill.error.BusinessException;
import com.zrq.secondkill.response.CommonReturnType;
import com.zrq.secondkill.service.SecurityService;
import com.zrq.secondkill.service.SessionService;
import com.zrq.secondkill.service.UserService;
import com.zrq.secondkill.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@CrossOrigin(allowCredentials="true", allowedHeaders = "*")
public class UserController {

    final
    UserService userService;

    final
    SecurityService securityService;

    final
    SessionService sessionService;

    public UserController(UserService userService, SecurityService securityService, SessionService sessionService) {
        this.userService = userService;
        this.securityService = securityService;
        this.sessionService = sessionService;
    }


    /**
     * 每次会新产生session,重新颁发新的token,覆盖就的token,但没有删除旧的session信息
     * @throws BusinessException
     */
    @PostMapping("/login")
    public CommonReturnType login(@RequestParam("telphone") String telphone,
                                  @RequestParam("password") String password
                                  ) throws BusinessException {
        UserModel userModel = userService.validateLogin(telphone, securityService.encodePassword(password));

        String token = sessionService.generateUniqueToken();
        sessionService.setAttribute(token,"isLogin",true);
        sessionService.setAttribute(token,"userModel",userModel);

        UserVO userVO = convertUserVOFromUserModel(userModel);
        userVO.setToken(token);
        return CommonReturnType.create(userVO);
    }

    private static UserVO convertUserVOFromUserModel(UserModel userModel) {
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userModel, userVO);
        return userVO;
    }

}
